package com.androidcentralmedias;

import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;

public class Server implements Runnable {
	public ArrayList<String> fila = new ArrayList<String>();
	public String ok_message;
	DatagramSocket theSocket = null;
	public Client client = new Client();

	public Server() {
		
		try {
			theSocket = new DatagramSocket(1236); //Server do Android e Client do PC na 1236
			// System.out.println("Server created and waiting for incomming connections...");
			Log.d("UDP","Server created and waiting for incomming connections...");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			Log.d("UDP","Error creating the socket: " + e.getMessage());
		}
		
	}

	public void run() {
		DatagramPacket theRecievedPacket;
		byte[] inBuffer;
		String type;
		String msg_id;
		ArrayList<String> lst_id = new ArrayList<String>();
		final int max_ids = 15;
		String try_message;
		String message;
		try {
			lst_id.add("0");
			// create some space for the text to send and recieve data
			inBuffer = new byte[500];
			// create a place for the client to send data too
			theRecievedPacket = new DatagramPacket(inBuffer, inBuffer.length);
			// wait for a client to request a connection
			while (true) {
				theSocket.receive(theRecievedPacket);
				if ( theRecievedPacket != null ) {
					try_message = new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength());
					Log.d("UDP",try_message);
					type = try_message.split("@")[0];
					//checa para ver se nao eh soh uma duplicata, uma vez q o programa do PC manda varias copias ate o android confirmar que chego alguma	
					if ( type.contains(MainActivity.type)) {
						ok_message = try_message;
					}
					else {
						msg_id = try_message.split("@")[1];
						if ( !lst_id.contains(msg_id)) {
							message = try_message.split("@")[2];
							//nesse caso a mensagem eh normal
							fila.add(message);
							Log.d("UDP",new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength()));
							//lembra do ultimo comando, para checar se eh duplicata
							lst_id.add(msg_id);
							if (lst_id.size() > max_ids )
								lst_id.remove(0);
						}
						//mesmo que for uma duplicata eh bom mandar o check para dizer ao programa do PC que o android recebeu a String
						Client.enviar(new String(theRecievedPacket.getData(), 0,theRecievedPacket.getLength()),type,1);
					}
				}
			}
		} catch (IOException ExceIO) {
			Log.d("UDP","Error with client request : "+ ExceIO.getMessage());
		}

		// close the server socket
		
	}

}

